package com.code.invoker;

import com.code.configs.CommonUnitEnum;
import com.code.invoker.base.AbstractBuilder;
import com.code.invoker.base.Invoker;
import com.code.invoker.base.SingleAbstractInvoker;
import com.code.utils.GeneratorUtil;
import com.code.utils.StringUtil;

import java.sql.SQLException;
import java.util.List;

public class SingleInvoker extends SingleAbstractInvoker {

    @Override
    protected void initTableInformation() {
        try {
            String tableName = this.tableInformation.getTableName();
            this.tableInformation.setTableInfos(this.connectionUtil.getMetaData1(tableName));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initTasks() {
        taskQueue.initSingleTasks(this.tableInformation);
    }

    public static class Builder extends AbstractBuilder {
        private SingleInvoker invoker = new SingleInvoker();

        public Builder setTableName(String tableName) {
            invoker.setTableName(tableName);
            return this;
        }

        public Builder setClassName(String className) {
            invoker.setClassName(className);
            return this;
        }

        public Builder setFlag(String flag) {
            List<String> units = CommonUnitEnum.getUnits(flag);
            invoker.setUnits(units);
            return this;
        }

        @Override
        public Invoker build() {
            if (!isParamtersValid()) {
                return null;
            }
            return invoker;
        }

        @Override
        public void checkBeforeBuild() throws Exception {
            if (StringUtil.isBlank(invoker.tableInformation.getTableName())) {
                throw new Exception("Expect table's name, but get a blank String.");
            }
            if (StringUtil.isBlank(invoker.tableInformation.getClassName())) {
                invoker.setClassName(GeneratorUtil.generateClassName(invoker.tableInformation.getTableName()));
            }
        }
    }

}
